<?php
if (isset($_GET['v']) && isset($_GET['token']) && ($_GET['v'] ==1 || $_GET['v'] ==2)) {
	
	mysql_connect("localhost", "root", "") or die(mysql_error());
	mysql_select_db("elections") or die(mysql_error());

	$v = mysql_real_escape_string($_GET['v']);
	$token = mysql_real_escape_string($_GET['token']);
	
	$result = mysql_query("SELECT * FROM tokens WHERE token='$token'")
	or die(mysql_error());  
	$num_rows = mysql_num_rows($result);
	if ($num_rows ==1) {
		
		$row = mysql_fetch_array($result);	
		$committee_no = $row['committee_no'];
		$index_no = $row['index_no'];
		
		$result = mysql_query("SELECT * FROM voters WHERE voted=0 AND token=1 AND index_no='$index_no' AND committee_no='$committee_no'")
		or die(mysql_error());
		$num_rows = mysql_num_rows($result);
		if ($num_rows ==1) {
			mysql_query("INSERT INTO votes (vote, date) VALUES ('$v',NOW())");
			mysql_query("UPDATE voters SET voted=1 WHERE index_no='$index_no' AND committee_no='$committee_no'");
			echo json_encode(array('succeed' => ''));
		} else {
			echo json_encode(array('error' => 'invalid token'));
		}
	} else {
		echo json_encode(array('error' => 'invalid token'));
	}
} else {
	echo json_encode(array('error' => 'token or vote choice was not provided'));
}
?>